package flex.cc.order.manage.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import flex.cc.sms.service.SendSmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import flex.cc.PubUtils;
import flex.cc.PublicUtil;
import flex.cc.basicinformation.dao.ServiceProviderDao;
import flex.cc.basicinformation.dao.ServiceProviderDataDao;
import flex.cc.basicinformation.entity.ChannelDataEntity;
import flex.cc.basicinformation.entity.ChannelEntity;
import flex.cc.basicinformation.entity.ServiceProviderDataEntity;
import flex.cc.basicinformation.entity.ServiceProviderEntity;
import flex.cc.basicinformation.service.ChannelService;
import flex.cc.common.Constants;
import flex.cc.common.utils.CommonUtils;
import flex.cc.common.utils.HttpClientUtil;
import flex.cc.common.utils.TypeConverUtils;
import flex.cc.common.vo.DelayedConfig;
import flex.cc.core.utils.RequestUtil;
import flex.cc.e2.util.HttpUtil;
import flex.cc.order.manage.dao.OrderTrackDao;
import flex.cc.order.manage.dto.order.OrderMainEntity;
import flex.cc.order.manage.dto.order.OrderServiceProviderEntity;
import flex.cc.order.manage.dto.order.OrderTrackEntity;
import flex.cc.order.manage.enums.StatusEnum;
import flex.cc.order.manage.enums.UpStatusEnum;
import flex.cc.order.manage.service.OrderMainService;
import flex.cc.order.manage.service.OrderServiceProviderService;
import flex.cc.order.manage.service.OrderServiceRescueService;
import flex.cc.order.manage.service.OrderTrackService;
import flex.cc.system.entity.DictCodeEntity;
import flex.cc.system.service.DictCodeService;
import flex.cc.util.DateUtil;
import flex.cc.util.EncryptionDecryption;
import flex.cc.vehicle_svr.model.SynStatusModel;
import flex.cc.vehicle_svr.vo.ResponseVo;

/**
 *
 * @author WANGCONG
 * 2021年9月6日下午4:59:56
 * @desc 服务单轨迹业务实现层
 */
@Service("orderTrackService")
public class OrderTrackServiceImpl extends ServiceImpl<OrderTrackDao, OrderTrackEntity> implements OrderTrackService{

	private static final Logger logger = LoggerFactory.getLogger(OrderTrackServiceImpl.class);

	@Resource
    private OrderTrackDao orderTrackDao;
	@Resource
	private OrderMainService orderMainService;
	@Resource
	private DictCodeService dictCodeService;
	@Value("${pengda.urgingRescue}")
    private String urgingRescue;
	@Value("${pengda.synStatus}")
    private String synStatus;
	@Value("${serviceprovider.pengda.serverName}")
	private String serverName;
	@Resource
	private ServiceProviderDao serviceProviderDao;
	@Resource
	private RedisTemplate<String, Object> redisTemplate;

	/**
	 * t_order_service_provider
	 * 受理内勤01传（状态回写接口）：更新worker_name
	 * 救援师傅名称03/04传，目前传固定值：鹏达救援（状态回写接口）：更新rescue_name
	 * 救援师傅电话03/04传，目前传固定值：客服电话（状态回写接口）：更新rescue_phone
	 * 预估救援服务费08传（状态回写接口）：更新fee
	 * （上游）实际救援服务金额：默认传值：0，salvationStatus救援单状态为：服务完成[COMPLETE] 时为实际救援服务金额，若空或救援单状态为其他状态时，传默认值：0
	 */
	@Resource
	private OrderServiceProviderService orderServiceProviderService;

	/**
	 * t_order_service_rescue
	 * 实际救援类型08传（状态回写接口），更新service_item
	 * 实际救援地址经度GCJ02坐标系；05传（状态回写接口），更新longitude
	 * 实际救援地址维度GCJ02坐标系；05传（状态回写接口），更新latitude
	 * 实际救援详细地址05传（状态回写接口），更新address
	 * 拖车出发经度06传且使用拖车了才传（状态回写接口），更新send_x
	 * 拖车出发维度06传且使用拖车了才传（状态回写接口），更新send_y
	 * 拖车到达经度06传且使用拖车了才传（状态回写接口），更新arrive_x
	 * 拖车到达经度06传且使用拖车了才传（状态回写接口），更新arrive_y
	 * 拖车距离（米）06传且使用拖车了才传（状态回写接口），更新drag_distance
	 */
	@Resource
	private OrderServiceRescueService orderServiceRescueService;
	@Resource
    private OrderTrackService orderTrackService;

	private static String CREATER = ""; //救援师傅，用于轨迹记录中的创建人
	@Resource
	private ServiceProviderDataDao serviceProviderDataDao;
	@Resource
	private ChannelService channelService;
	@Resource
	private SendSmsService sendSmsService;
	@Resource
	private AsyncUpCancellService asyncCancellService;

	/**
	 *
	 * @author WANGCONG
	 * 2021年9月7日上午10:44:32
	 * @desc 上游催单--->车服记录催单轨迹--->通知下游
	 */
	@Override
	public Map<String, Object> urgeOrder(Map<String, Object> jsonMap) {
		Map<String, Object> responseMap = new HashMap<>();
		//1.0车服系统插入催单记录
		OrderTrackEntity vo = new OrderTrackEntity();
		vo.setDataId(PubUtils.uuid());
		String orderNo = "";
		Map<String, Object> body = new HashMap<>(); //请求下游的body体
		body.put("content", jsonMap.get("content"));
		String flag = (String)jsonMap.get("flag");
		String temp_status = "";
		String updater = "";
		if("1".equals(flag)){//上游催单
			Map<String, Object> order_param = new HashMap<>();
			order_param.put("ownerOrderNo", (String)jsonMap.get("orderNo"));
			OrderMainEntity orderMain = orderMainService.getOneByParams(order_param);
			if(orderMain==null){
				responseMap.put("responseCode", "01");
				responseMap.put("responseMsg", "救援单号不存在");
				return responseMap;
			}
			orderNo = orderMain.getOrderNo();
			temp_status = orderMain.getStatus();
			String sourceName = orderMain.getSourceName();
			DictCodeEntity dictCodeEntity = dictCodeService.searchAllCodeByTypeCode("sourceName", sourceName, 0, null);
			updater = PublicUtil.isNotEmpty(dictCodeEntity) ? dictCodeEntity.getValue() : null;
		}else{//页面多选催单
			if("1".equals(jsonMap.get("oa"))) {
				updater ="CD";
			}else {
				updater = RequestUtil.getLoginUser().getUserName(); // 页面催单，对应的更新人是当前登录用户
			}
			orderNo = (String)jsonMap.get("orderNo");
		}
		
		vo.setOrderNo(orderNo);
		if("1".equals(jsonMap.get("oa"))) {
			vo.setTrackType("05");
			jsonMap.put("content","C端客户催单");
		}else {
			// 2022-03-14 10:39:54【2.2-服务包配置需求】救援单轨迹表新增备注类型：渠道商催单12、渠道商取消13
			if("1".equals(flag)) {//上游催单
				vo.setTrackType("12");
			} else {
				vo.setTrackType("02"); //轨迹类型：下单备注00、救援轨迹01、催单备注02、取消备注03，用于区分备注轨迹还是救援轨迹
			}
		}
		//轨迹描述：下单备注内容、救援轨迹描述、催单接口的催单内容、取消接口的取消原因
		vo.setTrackDesc(PublicUtil.isNotEmpty(jsonMap.get("content")) ? jsonMap.get("content").toString() : "");
		//以下两个字段，上游到下游可以为空，下游到上游，需赋值，用于计算是否为延时单和轨迹展示
		vo.setStatus(temp_status);
		vo.setServiceStatus("");
		vo.setCreateTime(new Date());
		vo.setUpdateTime(new Date());
		vo.setIsDelete(0);
		if (PublicUtil.isNotEmpty(updater)) {
			vo.setCreater(updater);
			vo.setUpdater(updater);
			jsonMap.remove("creater"); //对应下游报文，避免{msg=催单请求失败, code=500}
		}else{
			vo.setCreater("电话中心");
			vo.setUpdater("电话中心");
		}
		orderTrackDao.insert(vo);
		
		Map<String, Object> provider_param = new HashMap<>();
		provider_param.put("orderNo", orderNo);
		OrderServiceProviderEntity providerEntity = orderServiceProviderService.getOneByParams(provider_param);
		String servicerId = providerEntity.getServerId();
		List<ServiceProviderDataEntity> urlList = serviceProviderDataDao.queryListByYwId(servicerId);
		String urgeUrl = "";
    	for(int i=0; i<urlList.size(); i++){
    		if(Constants.urgingRescue.equals(urlList.get(i).getUrlType())){
    			urgeUrl = urlList.get(i).getUrl();
    			break;
    		}
    	}
    	if(PublicUtil.isEmpty(urgeUrl)){
    		responseMap.put("responseCode", "01");
            responseMap.put("responseMsg", "催单失败，未找到服务商催单接口地址");
            OrderTrackEntity trackVo = new OrderTrackEntity();
            trackVo.setDataId(PubUtils.uuid());
            trackVo.setOrderNo(orderNo);
            trackVo.setTrackType("02"); //轨迹类型：下单备注00、救援轨迹01、催单备注02、取消备注03，用于区分备注轨迹还是救援轨迹
            trackVo.setTrackDesc("催单失败，未找到服务商催单接口地址");
    		//以下两个字段，上游到下游可以为空，下游到上游，需赋值，用于计算是否为延时单和轨迹展示
            trackVo.setStatus(temp_status);
            trackVo.setServiceStatus("");
            trackVo.setCreateTime(new Date());
            trackVo.setUpdateTime(new Date());
            trackVo.setIsDelete(0);
    		if (PublicUtil.isNotEmpty(updater)) {
    			trackVo.setCreater(updater);
    			trackVo.setUpdater(updater);
    		}else{
    			trackVo.setCreater("电话中心");
    			trackVo.setUpdater("电话中心");
    		}
    		orderTrackDao.insert(trackVo);
            return responseMap;
    	}
    	
		body.put("orderNo", orderNo);
		
		//更新服务单催单记录加1
		Date currentTime = new Date();
		if("1".equals(jsonMap.get("oa"))) {
			orderMainService.addOaUrgeCount(orderNo, currentTime, currentTime, updater);
		}else {
			orderMainService.addUrgeCount(orderNo, currentTime, currentTime, updater); // 催单数量更新的同时，更新催单时间、更新时间和更新人。
		}
		
		
		try {
			//TODO 催单默认成功
			String result = CommonUtils.doPost(urgeUrl, CommonUtils.toJSONString(body));
			if(result == null || "".equals(result)){
				responseMap.put("responseCode", "01");
				responseMap.put("responseMsg", "失败");
				return responseMap;
			}
			JSONObject json = JSONObject.parseObject(result);
			Map<String, Object> m = new HashMap<>();
	        //循环转换
	        for(Map.Entry<String, Object> entry : json.entrySet()) {
	        	m.put(entry.getKey(), entry.getValue());
	        }
	        Integer code = (Integer) m.get("resultCode");
	        if(code.equals(ResponseVo.SUCCESS_CODE)){ //0
	        	responseMap.put("responseCode", "00");
				responseMap.put("responseMsg", "成功");
	        }else{
	        	responseMap.put("responseCode", "01");
				responseMap.put("responseMsg", PublicUtil.isNotEmpty(m.get("message")) ? m.get("message").toString() : "失败");
	        }
		} catch (Exception e) {
			responseMap.put("responseCode", "01");
			responseMap.put("responseMsg", "催单接口请求异常");
		}
		return responseMap;
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年9月7日下午1:30:29
	 * @desc 下游状态回写--->车服记录轨迹+更新服务单对应信息--->请求上游
	 */
	@SuppressWarnings("static-access")
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> synStatus(SynStatusModel statusVo) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		//1.根据救援单号，查询车服系统的信息
		String orderNo = statusVo.getOrderNo();
		Map<String, Object> order_param = new HashMap<>();
		order_param.put("orderNo", orderNo);
		OrderMainEntity orderMain = orderMainService.getOneByParams(order_param);
		if(orderMain==null){
			responseMap.put("resultCode", ResponseVo.ERROR_CODE);
			responseMap.put("message", "救援单号不存在");
			logger.info("状态回写下游报文:" + JSONObject.toJSONString(responseMap));
			return responseMap;
		}
		
		String sourceName = orderMain.getSourceName();  //渠道来源,00：自营、01：电话中心
		String main_status = orderMain.getStatus(); //主服务单状态

		// 0.对下游回传的救援人员进行转译。如果是空，则查该服务单对应的救援商，传对应的救援商名称。
		String rescueName = statusVo.getRescueName();
		logger.info("==================synStatus===============  orderNo = " + orderNo + ", 救援人员转译前 ==============> " + rescueName);
		if (PublicUtil.isNotEmpty(rescueName)) {
			Map<String, Object> serviceProviderParams = new HashMap<>();
			serviceProviderParams.put("shiftName", rescueName);
			ServiceProviderEntity serviceProviderEntity = serviceProviderDao.getOneByParams(serviceProviderParams);
			if (PublicUtil.isNotEmpty(serviceProviderEntity)) {
				rescueName = serviceProviderEntity.getServiceName();
			} else {
				rescueName = rescueName; // 如果服务商表中没有对应的转译，则显示传来的值
			}
		} else {
			// 如果状态回传接口没有传rescueName，根据服务单号，查询t_order_service_provider表，得到服务商id，再去t_service_provider表查服务商名称和转译名称
			Map<String, Object> orderServiceProviderParams = new HashMap<>();
			orderServiceProviderParams.put("orderNo", orderNo);
			OrderServiceProviderEntity orderServiceProviderByOrderNo = orderServiceProviderService.getOneByParams(orderServiceProviderParams);

			String serverId = orderServiceProviderByOrderNo.getServerId();
			logger.info("==================synStatus===============  orderNo = " + orderNo + ", 救援人员转译中 服务商id ==============> " + serverId);

			if (PublicUtil.isNotEmpty(serverId)) {
				Map<String, Object> serviceProviderParams = new HashMap<>();
				serviceProviderParams.put("id", serverId);
				ServiceProviderEntity serviceProviderEntity = serviceProviderDao.getOneByParams(serviceProviderParams);
				rescueName = serviceProviderEntity.getServiceName();
			}
		}
		statusVo.setRescueName(rescueName);
		logger.info("==================synStatus===============  orderNo = " + orderNo + ", 救援人员转译后 ==============> " + statusVo.getRescueName());

		//2.更新服务单对应的表字段
		/**
		 * 下游服务商状态：
		 * V2.0：01内勤受理02派单03救援师傅接单04改派05救援师傅出发06救援师傅到达现场开始作业07施救完成（拖车已拖至目的地）08师傅报备取消09任务结束
		 */
		String serviceStatus = statusVo.getStatus();
		serviceStatus = StatusEnum.getName(serviceStatus);
		String statusTime = statusVo.getStatusTime();
		Date statusDate = DateUtil.stringToDate(statusTime, "yyyy-MM-dd HH:mm:ss");

		Map<String, Object> body = new HashMap<String, Object>();
		Map<String, String> requestHeader = new HashMap<String, String>();
		Map<String, String> requestBody = new HashMap<String, String>();
		requestHeader.put("partnerCode", CommonUtils.PARTNERCODE);
		requestHeader.put("clientId", CommonUtils.CLIENTID);
		requestHeader.put("requestCode", "modifyStatus");
		body.put("requestHeader", requestHeader);
		requestBody.put("ownerOrderNo", orderMain.getOwnerOrderNo());

		if("00".equals(sourceName)){ //自营不回写上游
			responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
			responseMap.put("message", ResponseVo.SUCCESS_MSG);
			updateOwnParams(statusVo, orderMain);//更新车服系统对应的表字段
			insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);//插入轨迹信息
			sendSmsService.sendSms(orderMain.getOrderNo());
		}else{ //上游的服务单
			if("08".equals(main_status) || "09".equals(main_status)){ //已完成或者服务取消的单子
				if(!"09".equals(statusVo.getStatus())){ //本地做记录，不回传上游
					responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
					responseMap.put("message", ResponseVo.SUCCESS_MSG);
					updateOwnParams(statusVo, orderMain);//更新车服系统对应的表字段
					insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);//插入轨迹信息
				}else{ //只有09状态码时回写上游
					if("08".equals(main_status)){//如果单子是已完成状态，不回传上游
						responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
						responseMap.put("message", ResponseVo.SUCCESS_MSG);
						updateOwnParams(statusVo, orderMain);//更新车服系统对应的表字段
						insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);//插入轨迹信息
						return responseMap;
					}else{//取消动作
						//根据clientId去查渠道商信息
						Map<String, String> channelMap = new HashMap<>();
						channelMap.put("clientId", sourceName);
						List<ChannelEntity> channelList = channelService.findChannelByParam(channelMap);
						if(channelList.size()==0 || channelList==null){
							responseMap.put("resultCode", ResponseVo.ERROR_CODE);
							responseMap.put("message", "未找到渠道商");
							return responseMap;
						}
						String channelId = channelList.get(0).getId().toString();
						List<ChannelDataEntity> channelDataList = channelService.queryListByYwId(channelId);
						String synStatus_url = "";
						for(int i=0; i<channelDataList.size(); i++){
				    		if(Constants.synStatus.equals(channelDataList.get(i).getUrlType())){
				    			synStatus_url = channelDataList.get(i).getUrl();
				    			break;
				    		}
				    	}
						if(PublicUtil.isEmpty(synStatus_url)){
							responseMap.put("resultCode", ResponseVo.ERROR_CODE);
							responseMap.put("message", "渠道商状态回写接口地址未配置");
							return responseMap;
						}
						if(!Double.isNaN(statusVo.getFee())){ //工单取消-有空驶
							requestBody.put("salvationStatus", "CANCEL_COST");
						}else{
							int qxCount = orderTrackDao.queryQxCount(orderMain.getOrderNo());
							if(qxCount>0){ //派单后取消
								requestBody.put("salvationStatus", "CANCEL_AFTER_DISPATCHING");
							}else{
								requestBody.put("salvationStatus", "CANCEL_BEFORE_DISPATCHING"); //派单前取消
							}
						}
						requestBody.put("serviceAmount", PublicUtil.isNotEmpty(statusVo.getFee()) ? statusVo.getFee().toString() : "0");
						requestBody.put("serviceContent", "");  //服务商备注
						requestBody.put("cancelTime", statusTime);  //取消时间
						requestBody.put("cancelReason", PublicUtil.isNotEmpty(statusVo.getCancelReason()) ? statusVo.getCancelReason() : "");//服务商取消原因，07师傅报备取消时有值
						requestBody.put("statusTime", statusTime); //状态改变时间
						body.put("requestBody", requestBody);
						try {
							EncryptionDecryption des = new EncryptionDecryption();
							String jsonStr = JSON.toJSONString(body);
							System.out.println("加密前的回传报文=" + jsonStr);
							String jsonBody = des.encrypt(jsonStr);
							System.out.println("加密后的回传报文=" + jsonBody);
							String result = HttpClientUtil.sendHttpPost(synStatus_url, jsonBody, null);
							System.out.println("渠道商返回响应加密报文=" + result);
							if(result == null || "".equals(result)){
								responseMap.put("resultCode", ResponseVo.ERROR_CODE);
								responseMap.put("message", "渠道商状态回写接口调用失败");
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, CREATER, 1);
								return responseMap;
							}
							result = des.decrypt(result.trim(), "UTF-8");
							System.out.println("渠道商返回响应报文解密=" + result);
							JSONObject json = JSONObject.parseObject(result);
					        String code =  json.get("responseCode").toString();
					        if("00".equals(code)){ //00
					        	responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
								responseMap.put("message", ResponseVo.SUCCESS_MSG);
								//更新车服系统对应的表字段
								updateOwnParams(statusVo, orderMain);
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
								// 状态回写成功后根据服务单状态，判断是否给客户发送对应的通知短信
								sendSmsService.sendSms(orderMain.getOrderNo());
							}else{
					        	responseMap.put("resultCode", ResponseVo.ERROR_CODE);
								responseMap.put("message", ResponseVo.ERROR_MSG);
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
					        }
						} catch (Exception e) {
							responseMap.put("resultCode", ResponseVo.ERROR_CODE);
							responseMap.put("message", "数据处理异常");
							//插入轨迹信息
							insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
						}
					}
				}
			}else{

				if("08".equals(statusVo.getStatus()) || "05".equals(statusVo.getStatus())){ //08师傅报备取消、05师傅出发时，只改变车服状态，不回传上游
					responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
					responseMap.put("message", ResponseVo.SUCCESS_MSG);
					updateOwnParams(statusVo, orderMain);//更新车服系统对应的表字段
					insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);//插入轨迹信息
					sendSmsService.sendSms(orderMain.getOrderNo());
				}else{
					if("09".equals(statusVo.getStatus())){ //09任务结束，判断"工单取消-有空驶"、"派单后取消"、"派单前取消"、"服务完成"
						if("08".equals(main_status)){//如果单子是已完成状态，不回传上游
							responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
							responseMap.put("message", ResponseVo.SUCCESS_MSG);
							updateOwnParams(statusVo, orderMain);//更新车服系统对应的表字段
							insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);//插入轨迹信息
							return responseMap;
						}else{//取消动作
							if(!Double.isNaN(statusVo.getFee())){ //工单取消-有空驶
								requestBody.put("salvationStatus", "CANCEL_COST");
							}else{
								int qxCount = orderTrackDao.queryQxCount(orderMain.getOrderNo());
								if(qxCount>0){ //派单后取消
									requestBody.put("salvationStatus", "CANCEL_AFTER_DISPATCHING");
								}else{
									requestBody.put("salvationStatus", "CANCEL_BEFORE_DISPATCHING"); //派单前取消
								}
							}
						}
					}else{
						String upStatus = UpStatusEnum.getName(statusVo.getStatus()); //拿到上游对应的状态码
						requestBody.put("salvationStatus", upStatus);
					}
					requestBody.put("serviceAmount", PublicUtil.isNotEmpty(statusVo.getFee()) ? statusVo.getFee().toString() : "0");
					requestBody.put("serviceContent", "");  //服务商备注
					requestBody.put("cancelTime", statusTime);  //取消时间
					requestBody.put("cancelReason", PublicUtil.isNotEmpty(statusVo.getCancelReason()) ? statusVo.getCancelReason() : "");//服务商取消原因，07师傅报备取消时有值
					requestBody.put("statusTime", statusTime); //状态改变时间
					body.put("requestBody", requestBody);
					
					//根据clientId去查渠道商信息
					Map<String, String> channelMap = new HashMap<>();
					channelMap.put("clientId", sourceName);
					List<ChannelEntity> channelList = channelService.findChannelByParam(channelMap);
					if(channelList.size()==0 || channelList==null){
						responseMap.put("resultCode", ResponseVo.ERROR_CODE);
						responseMap.put("message", "未找到渠道商");
						return responseMap;
					}
					String channelId = channelList.get(0).getId().toString();
					List<ChannelDataEntity> channelDataList = channelService.queryListByYwId(channelId);
					String synStatus_url = "";
					for(int i=0; i<channelDataList.size(); i++){
			    		if(Constants.synStatus.equals(channelDataList.get(i).getUrlType())){
			    			synStatus_url = channelDataList.get(i).getUrl();
			    			break;
			    		}
			    	}
					if(PublicUtil.isEmpty(synStatus_url)){
						responseMap.put("resultCode", ResponseVo.ERROR_CODE);
						responseMap.put("message", "渠道商状态回写接口地址未配置");
						return responseMap;
					}
					
					try {
						EncryptionDecryption des = new EncryptionDecryption();
						String jsonStr = JSON.toJSONString(body);
						System.out.println("加密前的回传报文=" + jsonStr);
						String jsonBody = des.encrypt(jsonStr);
						System.out.println("加密后的回传报文=" + jsonBody);
						String result = HttpClientUtil.sendHttpPost(synStatus_url, jsonBody, null);
						System.out.println("渠道商返回响应加密报文=" + result);
						if(result == null || "".equals(result)){
							responseMap.put("resultCode", ResponseVo.ERROR_CODE);
							responseMap.put("message", "渠道商状态回写接口调用失败");
							//插入轨迹信息
							insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, CREATER, 1);
							return responseMap;
						}
						result = des.decrypt(result.trim(), "UTF-8");
						System.out.println("渠道商返回响应报文解密=" + result);
						JSONObject json = JSONObject.parseObject(result);
				        String code =  json.get("responseCode").toString();
				        if("00".equals(code)){ //00
				        	responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
							responseMap.put("message", ResponseVo.SUCCESS_MSG);
							//更新车服系统对应的表字段
							updateOwnParams(statusVo, orderMain);
							//插入轨迹信息
							insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
							sendSmsService.sendSms(orderMain.getOrderNo());
				        }else{
				        	responseMap.put("resultCode", ResponseVo.ERROR_CODE);
							responseMap.put("message", ResponseVo.ERROR_MSG);
							//插入轨迹信息
							insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
				        }
					} catch (Exception e) {
						responseMap.put("resultCode", ResponseVo.ERROR_CODE);
						responseMap.put("message", "数据处理异常");
						//插入轨迹信息
						insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
					}
				}
			}

		}
		return responseMap;
	}

	//2021年9月16日10:09:38  保存状态回写轨迹记录
	//flag：0:成功标识，1:失败标识
	public void insertSynStatusTrack(OrderMainEntity orderMain, SynStatusModel statusVo, String main_status,
			String serviceStatus, Date statusDate, String creater, int flag) {
		String track_status = "";
		if("1".equals(flag)){
			track_status = main_status;
		}else{
			switch (statusVo.getStatus()) {
			case "01": // 内勤受理
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					track_status = "02";
				}else{
					track_status = main_status;
				}
				break;
			case "02": // 派单
				CREATER = statusVo.getWorkerName();
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					track_status = "03";
				}else{
					track_status = main_status;
				}
				break;
			case "03": // 救援师傅接单
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					track_status = "04";
				}else{
					track_status = main_status;
				}
				break;
			case "04": // 改派
				CREATER = statusVo.getWorkerName();
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					track_status = "04";
				}else{
					track_status = main_status;
				}
				break;
			case "05": // 05救援师傅出发
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					track_status = "05";
				}else{
					track_status = main_status;
				}
				break;
			case "06": // 救援师傅到达现场开始作业
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					track_status = "06";
				}else{
					track_status = main_status;
				}
				break;
			case "07": // 施救完成（拖车已拖至目的地）
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					track_status = "08";
				}else{
					track_status = main_status;
				}
				break;
			case "08": // 师傅报备取消
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					track_status = "09";
				}else{
					track_status = main_status;
				}
				break;
			case "09": // 任务结束
				track_status = main_status;
				break;
			}
		}
		OrderTrackEntity vo = new OrderTrackEntity();
		vo.setDataId(PubUtils.uuid());
		vo.setOrderNo(orderMain.getOrderNo());
		vo.setTrackType("01"); // 轨迹类型：下单备注00、救援轨迹01、催单备注02、取消备注03，用于区分备注轨迹还是救援轨迹
		vo.setTrackDesc(statusVo.getCancelReason());// 轨迹描述：下单备注内容、救援轨迹描述、催单接口的催单内容、取消接口的取消原因
		// 以下两个字段，上游到下游可以为空，下游到上游，需赋值，用于计算是否为延时单和轨迹展示
		vo.setStatus(track_status); // 服务单主表的状态码
		vo.setServiceStatus(serviceStatus);
		vo.setCreateTime(new Date());
		vo.setUpdateTime(new Date());
		vo.setCreater(creater);
		vo.setUpdater(creater);
		vo.setIsDelete(flag);
		if(PublicUtil.isEmpty(statusDate)){
			vo.setSynTime(new Date());
		}else{
			vo.setSynTime(statusDate); //报文中的时间
		}
		orderTrackDao.insert(vo);
	}

	/**
	 * @param orderTrackEntity
	 * @return
	 * @description 添加一条记录
	 * @author wkangle
	 * @time 2021/09/08 0008 8:58
	 * @exception/throws
	 */
	@Override
	public int insert(OrderTrackEntity orderTrackEntity) {
		return orderTrackDao.insert(orderTrackEntity);
	}

	/**
	 * @param params 查询条件
	 * @return
	 * @description 根据查询条件查询服务单轨迹信息
	 * @author wkangle
	 * @time 2021/09/08 0008 9:12
	 * @exception/throws
	 */
	@Override
	public OrderTrackEntity getOneByParams(Map<String, Object> params) {
		return orderTrackDao.getOneByParams(params);
	}

	/**
	 * @param params 查询条件
	 * @return
	 * @description 根据查询条件得到轨迹列表
	 * @author wkangle
	 * @time 2021/09/08 0008 18:40
	 * @exception/throws
	 */
	@Override
	public List<OrderTrackEntity> getListByParams(Map<String, Object> params) {
		return orderTrackDao.getListByParams(params);
	}

	public void updateOwnParams(SynStatusModel statusVo, OrderMainEntity orderMain) {
		String dataId = orderMain.getDataId(); //车服系统主键，用于更新服务单主表信息

		String serviceStatus = statusVo.getStatus();
		serviceStatus = StatusEnum.getName(serviceStatus);
		String statusTime = statusVo.getStatusTime();
		Date statusDate = DateUtil.stringToDate(statusTime, "yyyy-MM-dd HH:mm:ss");
		String main_status = orderMain.getStatus();

		Map<String,Object> params = new HashMap<>(); //查询map参数集合
		int differ = 0; //存时间差，判断是否为延时单
		Map<String, Object> provider_param = new HashMap<>(); //更新t_order_service_provider表参数
		Map<String, Object> rescue_param = new HashMap<>();   //更新t_order_service_rescue表参数

		// 救援人员转译：鹏达救援 ==> 救援商A，值取自服务商表中存的救援商转译
		String rescueName = statusVo.getRescueName();
		if (PublicUtil.isNotEmpty(rescueName)) {
			Map<String, Object> rescueNameParam = new HashMap<>();
			rescueNameParam.put("shiftName", rescueName);
			ServiceProviderEntity serviceProviderEntity = serviceProviderDao.getOneByParams(rescueNameParam);
			if (PublicUtil.isNotEmpty(serviceProviderEntity)) {
				rescueName = serviceProviderEntity.getServiceName();
			}
		} else {
			rescueName = serverName; // TODO 经确认，若没有传救援人员，则默认为救援商A
		}

		//该为不判断状态码，有值就更新，没值不更新
		provider_param.put("workerName", statusVo.getWorkerName());
		provider_param.put("orderNo", orderMain.getOrderNo());
		provider_param.put("rescueName", rescueName);
		provider_param.put("rescuePhone", statusVo.getRescuePhone());
		provider_param.put("fee", statusVo.getFee());
		orderServiceProviderService.updateByParams(provider_param);
		rescue_param.put("orderNo", orderMain.getOrderNo());
		rescue_param.put("sendX", statusVo.getSendX());
		rescue_param.put("sendY", statusVo.getSendY());
		rescue_param.put("arriveX", statusVo.getArriveX());
		rescue_param.put("arriveY", statusVo.getArriveY());
		rescue_param.put("endX", statusVo.getArriveX()); //新增的endX、endY，完成（拖车目的地）经纬度
		rescue_param.put("endY", statusVo.getArriveY());
		rescue_param.put("dragDistance", statusVo.getDragDistance());
		rescue_param.put("rescueDistance", statusVo.getDragDistance());
		rescue_param.put("serviceItem", statusVo.getServiceItem());
		rescue_param.put("longitude", statusVo.getLongitude());
		rescue_param.put("latitude", statusVo.getLatitude());
		rescue_param.put("address", statusVo.getAddress());
		orderServiceRescueService.updateByParams(rescue_param);

		switch (statusVo.getStatus()) {
			case "01": // 内勤受理
				CREATER = statusVo.getWorkerName();
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					orderMainService.updateStatus(dataId, "02", new Date(), statusVo.getRescueName());// 更新服务单主表状态：待处理--->已受理
				}
				break;
			case "02": // 派单
				CREATER = statusVo.getWorkerName();
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					orderMainService.updateStatus(dataId, "03", new Date(), statusVo.getRescueName());// 更新服务单主表状态：已派单
				}
				break;
			case "03": // 救援师傅接单
				CREATER = rescueName;
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					orderMainService.updateStatus(dataId, "04", new Date(), statusVo.getRescueName());// 更新服务单主表状态：已接单
				}
				// 查找服务单在'已受理'状态时的轨迹时间，计算时间差，处理时长超过5分钟则为延时单
				params.put("orderNo", orderMain.getOrderNo());
//				params.put("status", "01");
//				params.put("synTime", "synTime");
				params.put("trackType", "01");
				params.put("serviceStatus", "内勤受理");
				OrderTrackEntity orderTrackEntity = this.getOneByParams(params);
				if (orderTrackEntity != null) {
					Date synTime = orderTrackEntity.getSynTime();
					differ = DateUtil.getIntervalFen(synTime, statusDate);
					if (differ >= DelayedConfig.ONE /*&& orderMain.getIsDalayed() == 0*/) { // 更新服务单主表信息延时标识
						orderMainService.updateDelayedFlag(dataId);
					}else if(differ < DelayedConfig.ONE/* && orderMain.getIsDalayed() == 1*/){//将延时标识取消
						orderMainService.delDelayedFlag(dataId);
					}
				}
				break;
			case "04": // 改派
				CREATER = rescueName;
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					orderMainService.updateStatus(dataId, "04", new Date(), statusVo.getRescueName());// 更新服务单主表状态：已接单
				}
				break;
			case "05": // 05救援师傅出发
				CREATER = rescueName;
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					orderMainService.updateStatus(dataId, "05", new Date(), statusVo.getRescueName());// 更新服务单主表状态：开始出发
				}
				break;
			case "06": // 救援师傅到达现场开始作业
				CREATER = rescueName;
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					orderMainService.updateStatus(dataId, "06", new Date(), statusVo.getRescueName());// 更新服务单主表状态：到达现场
				}
				// 查找服务单在'已接单'状态时的轨迹时间，计算时间差，处理时长超过45分钟则为延时单
				params.put("orderNo", orderMain.getOrderNo());
//				params.put("status", "04");
//				params.put("synTime", "synTime");
				params.put("trackType", "01");
				params.put("serviceStatus", "救援师傅接单");
				orderTrackEntity = this.getOneByParams(params);
				if (orderTrackEntity != null) {
					Date synTime = orderTrackEntity.getSynTime();
					differ = DateUtil.getIntervalFen(synTime, statusDate);
					if (differ >= DelayedConfig.TWO/* && orderMain.getIsDalayed() == 0*/) { // 延时单标识，默认0-非延时，1-延时
						orderMainService.updateDelayedFlag(dataId);// 更新服务单主表信息延时标识
					}else if(differ < DelayedConfig.TWO && orderMain.getIsDalayed() == 2){//将延时标识取消
						orderMainService.delDelayedFlag(dataId);
					}
				}
				break;
			case "07": // 施救完成（拖车已拖至目的地）
				CREATER = rescueName;
				// 更新服务单主表状态：已完成
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					orderMainService.updateStatus(dataId, "08", new Date(), statusVo.getRescueName());// 更新服务单主表状态：已完成
				}
				break;
			case "08": // 师傅报备取消
				CREATER = rescueName;
				if( !("08".equals(main_status) || "09".equals(main_status)) ){
					orderMainService.updateStatus(dataId, "09", new Date(), statusVo.getRescueName());// 更新服务单主表状态：服务取消
				}
				break;
			case "09": // 任务结束
				CREATER = rescueName;
				//orderMainService.updateStatus(dataId, "08");// 更新服务单主表状态：已完成
				break;
			default:
				break;
		}
		logger.info("---------------------本地状态更新成功---------------------");
	}
    
	@Override
	public List<OrderTrackEntity> selectOrderTrackList(String orderNo) {
		List<OrderTrackEntity>task= orderTrackDao.selectOrderTrackList(orderNo);
		return task;
	}
	
	//-----------------------------------------------------------状态回写V2.0-----------------------------------------------------------//
	/**
	 *
	 * @author WANGCONG
	 * 2021年12月31日下午15:21:08
	 * @version 2.0
	 * @desc 下游状态回写
	 */
	@SuppressWarnings("static-access")
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> synStatus_V2(SynStatusModel statusVo) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		//1.根据救援单号，查询车服系统的信息
		String orderNo = statusVo.getOrderNo();
		if(redisTemplate.hasKey(orderNo)){
			responseMap.put("resultCode", ResponseVo.ERROR_CODE);
			responseMap.put("message", "救援单号不存在");
			return responseMap;
		}
		Map<String, Object> order_param = new HashMap<>();
		order_param.put("orderNo", orderNo);
		OrderMainEntity orderMain = orderMainService.getOneByParams(order_param);
		if(orderMain==null){
			redisTemplate.opsForValue().set(orderNo, orderNo, 10, TimeUnit.SECONDS);
			responseMap.put("resultCode", ResponseVo.ERROR_CODE);
			responseMap.put("message", "救援单号不存在");
			logger.info("状态回写下游报文:" + JSONObject.toJSONString(responseMap));
			return responseMap;
		}
		String cancelChannel = orderMain.getCancelChannel(); //取消渠道：1-上游，2-下游，3-车服，4-C端
		String sourceName = orderMain.getSourceName();  //渠道来源,00：自营、01：电话中心
		String main_status = orderMain.getStatus(); //主服务单状态
		// 0.对下游回传的救援人员进行转译。如果是空，则查该服务单对应的救援商，传对应的救援商名称。
		String rescueName = statusVo.getRescueName();
		logger.info("==================synStatus===============  orderNo = " + orderNo + ", 救援人员转译前 ==============> " + rescueName);
		if (PublicUtil.isNotEmpty(rescueName)) {
			Map<String, Object> serviceProviderParams = new HashMap<>();
			serviceProviderParams.put("shiftName", rescueName);
			ServiceProviderEntity serviceProviderEntity = serviceProviderDao.getOneByParams(serviceProviderParams);
			if (PublicUtil.isNotEmpty(serviceProviderEntity)) {
				rescueName = serviceProviderEntity.getServiceName();
			} else {
				rescueName = rescueName; // 如果服务商表中没有对应的转译，则显示传来的值
			}
		} else {
			// 如果状态回传接口没有传rescueName，根据服务单号，查询t_order_service_provider表，得到服务商id，再去t_service_provider表查服务商名称和转译名称
			Map<String, Object> orderServiceProviderParams = new HashMap<>();
			orderServiceProviderParams.put("orderNo", orderNo);
			OrderServiceProviderEntity orderServiceProviderByOrderNo = orderServiceProviderService.getOneByParams(orderServiceProviderParams);
			String serverId = orderServiceProviderByOrderNo.getServerId();
			logger.info("==================synStatus===============  orderNo = " + orderNo + ", 救援人员转译中 服务商id ==============> " + serverId);
			if (PublicUtil.isNotEmpty(serverId)) {
				Map<String, Object> serviceProviderParams = new HashMap<>();
				serviceProviderParams.put("id", serverId);
				ServiceProviderEntity serviceProviderEntity = serviceProviderDao.getOneByParams(serviceProviderParams);
				rescueName = serviceProviderEntity.getServiceName();
			}
		}
		statusVo.setRescueName(rescueName);
		logger.info("==================synStatus===============  orderNo = " + orderNo + ", 救援人员转译后 ==============> " + statusVo.getRescueName());
		//2.更新服务单对应的表字段
		/**
		 * 下游服务商状态：
		 * V2.0：01内勤受理02派单03救援师傅接单04改派05救援师傅出发06救援师傅到达现场开始作业07施救完成（拖车已拖至目的地）08师傅报备取消09任务结束
		 */
		String serviceStatus = statusVo.getStatus();
		serviceStatus = StatusEnum.getName(serviceStatus);
		String statusTime = statusVo.getStatusTime();
		Date statusDate = DateUtil.stringToDate(statusTime, "yyyy-MM-dd HH:mm:ss");

		Map<String, Object> body = new HashMap<String, Object>();
		Map<String, String> requestHeader = new HashMap<String, String>();
		Map<String, String> requestBody = new HashMap<String, String>();
		requestHeader.put("partnerCode", CommonUtils.PARTNERCODE);
		requestHeader.put("clientId", CommonUtils.CLIENTID);
		requestHeader.put("requestCode", "modifyStatus");
		body.put("requestHeader", requestHeader);
		requestBody.put("ownerOrderNo", orderMain.getOwnerOrderNo());
		//根据clientId去查渠道商信息
		Map<String, String> channelMap = new HashMap<>();
		channelMap.put("clientId", sourceName);
		List<ChannelEntity> channelList = channelService.findChannelByParam(channelMap);
		if(channelList.size()==0 || channelList==null){
			responseMap.put("resultCode", ResponseVo.ERROR_CODE);
			responseMap.put("message", "未找到渠道商");
			return responseMap;
		}
		String channelId = channelList.get(0).getId().toString();
		List<ChannelDataEntity> channelDataList = channelService.queryListByYwId(channelId);
		String synStatus_url = "";    //上游状态回写接口地址
		for(int i=0; i<channelDataList.size(); i++){
    		if(Constants.synStatus.equals(channelDataList.get(i).getUrlType())){
    			synStatus_url = channelDataList.get(i).getUrl();
    			break;
    		}
    	}
		if(PublicUtil.isEmpty(synStatus_url)){
			responseMap.put("resultCode", ResponseVo.ERROR_CODE);
			responseMap.put("message", "渠道商状态回写接口地址未配置");
			return responseMap;
		}
		
		if("00".equals(sourceName)){ //自营不回写上游
			responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
			responseMap.put("message", ResponseVo.SUCCESS_MSG);
			updateOwnParams_V2(statusVo, orderMain);//更新车服系统对应的表字段
			insertSynStatusTrack_V2(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);//插入轨迹信息
			sendSmsService.sendSms(orderMain.getOrderNo());
		}else{ //上游的服务单
			if(sourceName.equals("02")){
				responseMap = synStatus_ZH(statusVo,orderMain,synStatus_url);
			}else{
				//已完成、取消有费用、取消无费用的不做处理，只记录轨迹
				if("08".equals(main_status)||"10".equals(main_status)||"11".equals(main_status)){
					responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
					responseMap.put("message", ResponseVo.SUCCESS_MSG);
					insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);//插入轨迹信息
				}else if("09".equals(main_status)){//服务取消，说明上游、C端已触发过取消
					if("08".equals(statusVo.getStatus())|| "09".equals(statusVo.getStatus())){//下游回写师傅报备取消或任务结束，调上游回写状态和取消接口
						Double judgeField = "08".equals(statusVo.getStatus())?statusVo.getVainDistance():statusVo.getFee();
						judgeField = judgeField == null ? 0 : judgeField;
						String temp_judgeField = String.valueOf(judgeField);
						BigDecimal decimal =new BigDecimal(temp_judgeField);
						
						try {
							if(decimal.compareTo(new BigDecimal(0))>0){
								requestBody.put("salvationStatus", "CANCEL_COST");//工单取消-有空驶
							}else{
								int qxCount = orderTrackDao.queryQxCount(orderMain.getOrderNo());
								if(qxCount>0){
									requestBody.put("salvationStatus", "CANCEL_AFTER_DISPATCHING");//派单后取消
								}else{
									requestBody.put("salvationStatus", "CANCEL_BEFORE_DISPATCHING"); //派单前取消
								}
							}
							requestBody.put("serviceAmount", PublicUtil.isNotEmpty(statusVo.getFee()) ? statusVo.getFee().toString() : "0");
							requestBody.put("serviceContent", "");  //服务商备注
							requestBody.put("cancelTime", DateUtil.DateToString(new Date()));  //取消时间
							requestBody.put("cancelReason", PublicUtil.isNotEmpty(statusVo.getCancelReason()) ? statusVo.getCancelReason() : "");//服务商取消原因，07师傅报备取消时有值
							requestBody.put("statusTime", statusTime); //状态改变时间
							body.put("requestBody", requestBody);
							EncryptionDecryption des = new EncryptionDecryption();
							String jsonStr = JSON.toJSONString(body);
							logger.info("加密前的回传报文=" + jsonStr);
							String jsonBody = des.encrypt(jsonStr);
							logger.info("加密后的回传报文=" + jsonBody);
							String result = HttpClientUtil.sendHttpPost(synStatus_url, jsonBody, null);
							logger.info("渠道商返回响应加密报文=" + result);
							if(result == null || "".equals(result)){
								responseMap.put("resultCode", ResponseVo.ERROR_CODE);
								responseMap.put("message", "渠道商状态回写接口调用失败");
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, CREATER, 1);
								return responseMap;
							}
							result = des.decrypt(result.trim(), "UTF-8");
							logger.info("渠道商返回响应报文解密=" + result);
							JSONObject json = JSONObject.parseObject(result);
					        String code =  json.get("responseCode").toString();
					        if("00".equals(code)){ //00
					        	responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
								responseMap.put("message", ResponseVo.SUCCESS_MSG);
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
								// 状态回写成功后根据服务单状态，判断是否给客户发送对应的通知短信
								updateOwnParams_V2(statusVo, orderMain);//更新车服系统对应的表字段
								sendSmsService.sendSms(orderMain.getOrderNo());
								if(!"1".equals(cancelChannel) && !"3".equals(cancelChannel)){//取消渠道：1-上游，2-下游，3-车服，4-C端
									//TODO 下游取消或C端取消，异步调用上游取消接口
									asyncCancellService.asyncCancell(channelDataList, statusVo, orderMain, requestBody.get("salvationStatus"), cancelChannel);
								}
							}else{
					        	responseMap.put("resultCode", ResponseVo.ERROR_CODE);
								responseMap.put("message", ResponseVo.ERROR_MSG);
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
					        }
						} catch (Exception e) {
							responseMap.put("resultCode", ResponseVo.ERROR_CODE);
							responseMap.put("message", "数据处理异常");
							//插入轨迹信息
							insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
						}
					}else{//服务取消状态下，回写的其它状态码，车服只记录轨迹
						responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
						responseMap.put("message", ResponseVo.SUCCESS_MSG);
						insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);//插入轨迹信息
					}
				}else{//服务单中间状态
					if("05".equals(statusVo.getStatus())){ //05-师傅出发时，只改变车服状态，不回传上游
						responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
						responseMap.put("message", ResponseVo.SUCCESS_MSG);
						updateOwnParams(statusVo, orderMain);//更新车服系统对应的表字段
						insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);//插入轨迹信息
						sendSmsService.sendSms(orderMain.getOrderNo());
					}else if("09".equals(statusVo.getStatus())){//下游回写任务结束，此逻辑不通（正常情况下不会出现）
						responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
						responseMap.put("message", ResponseVo.SUCCESS_MSG);
						insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);//插入轨迹信息
					}else if("08".equals(statusVo.getStatus())){//下游回写师傅报备取消，调上游回写接口和取消接口
						Double judgeField = PublicUtil.isNotEmpty(statusVo.getVainDistance()) ? statusVo.getVainDistance() : 0d;
						String temp_judgeField = String.valueOf(judgeField);
						BigDecimal decimal =new BigDecimal(temp_judgeField);
						
						try {

							if(decimal.compareTo(new BigDecimal(0))>0){
								requestBody.put("salvationStatus", "CANCEL_COST");//工单取消-有空驶
							}else{
								int qxCount = orderTrackDao.queryQxCount(orderMain.getOrderNo());
								if(qxCount>0){
									requestBody.put("salvationStatus", "CANCEL_AFTER_DISPATCHING");//派单后取消
								}else{
									requestBody.put("salvationStatus", "CANCEL_BEFORE_DISPATCHING"); //派单前取消
								}
							}
							requestBody.put("serviceAmount", PublicUtil.isNotEmpty(statusVo.getFee()) ? statusVo.getFee().toString() : "0");
							requestBody.put("serviceContent", "");  //服务商备注
							requestBody.put("cancelTime", statusTime);  //取消时间
							requestBody.put("cancelReason", PublicUtil.isNotEmpty(statusVo.getCancelReason()) ? statusVo.getCancelReason() : "");//服务商取消原因，07师傅报备取消时有值
							requestBody.put("statusTime", statusTime); //状态改变时间
							body.put("requestBody", requestBody);
							EncryptionDecryption des = new EncryptionDecryption();
							String jsonStr = JSON.toJSONString(body);
							logger.info("加密前的回传报文=" + jsonStr);
							String jsonBody = des.encrypt(jsonStr);
							logger.info("加密后的回传报文=" + jsonBody);
							String result = HttpClientUtil.sendHttpPost(synStatus_url, jsonBody, null);
							logger.info("渠道商返回响应加密报文=" + result);
							if(result == null || "".equals(result)){
								responseMap.put("resultCode", ResponseVo.ERROR_CODE);
								responseMap.put("message", "渠道商状态回写接口调用失败");
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, CREATER, 1);
								return responseMap;
							}
							result = des.decrypt(result.trim(), "UTF-8");
							logger.info("渠道商返回响应报文解密=" + result);
							JSONObject json = JSONObject.parseObject(result);
					        String code =  json.get("responseCode").toString();
					        if("00".equals(code)){ //00
					        	responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
								responseMap.put("message", ResponseVo.SUCCESS_MSG);
								updateOwnParams_V2(statusVo, orderMain);//更新车服系统对应的表字段
								//更新t_order_main表cancel_channel字段为：2-下游发起取消
								orderMainService.updateCancelChannel(orderMain.getDataId(), new Date(), "2");
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
								// 状态回写成功后根据服务单状态，判断是否给客户发送对应的通知短信
								sendSmsService.sendSms(orderMain.getOrderNo());
								//TODO 下游发起取消，调用上游取消接口
								asyncCancellService.asyncCancell(channelDataList, statusVo, orderMain, requestBody.get("salvationStatus"), "2");
							}else{
					        	responseMap.put("resultCode", ResponseVo.ERROR_CODE);
								responseMap.put("message", ResponseVo.ERROR_MSG);
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
					        }
						} catch (Exception e) {
							responseMap.put("resultCode", ResponseVo.ERROR_CODE);
							responseMap.put("message", "数据处理异常");
							//插入轨迹信息
							insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
						}
					}else{ //下游回写的其它状态，直接回写上游
						try {

							String upStatus = UpStatusEnum.getName(statusVo.getStatus()); //拿到上游对应的状态码
							requestBody.put("salvationStatus", upStatus);
							requestBody.put("serviceAmount", PublicUtil.isNotEmpty(statusVo.getFee()) ? statusVo.getFee().toString() : "0");
							requestBody.put("serviceContent", "");  //服务商备注
							requestBody.put("cancelTime", "");  //中间状态，取消时间不传
							requestBody.put("cancelReason", PublicUtil.isNotEmpty(statusVo.getCancelReason()) ? statusVo.getCancelReason() : "");//服务商取消原因，07师傅报备取消时有值
							requestBody.put("statusTime", statusTime); //状态改变时间
							body.put("requestBody", requestBody);
							EncryptionDecryption des = new EncryptionDecryption();
							String jsonStr = JSON.toJSONString(body);
							logger.info("加密前的回传报文=" + jsonStr);
							String jsonBody = des.encrypt(jsonStr);
							logger.info("加密后的回传报文=" + jsonBody);
							String result = HttpClientUtil.sendHttpPost(synStatus_url, jsonBody, null);
							logger.info("渠道商返回响应加密报文=" + result);
							if(result == null || "".equals(result)){
								responseMap.put("resultCode", ResponseVo.ERROR_CODE);
								responseMap.put("message", "渠道商状态回写接口调用失败");
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, CREATER, 1);
								return responseMap;
							}
							result = des.decrypt(result.trim(), "UTF-8");
							logger.info("渠道商返回响应报文解密=" + result);
							JSONObject json = JSONObject.parseObject(result);
					        String code =  json.get("responseCode").toString();
					        if("00".equals(code)){ //00
					        	responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
								responseMap.put("message", ResponseVo.SUCCESS_MSG);
								//更新车服系统对应的表字段
								updateOwnParams(statusVo, orderMain);
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
								sendSmsService.sendSms(orderMain.getOrderNo());
					        }else{
					        	responseMap.put("resultCode", ResponseVo.ERROR_CODE);
								responseMap.put("message", ResponseVo.ERROR_MSG);
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
					        }
						} catch (Exception e) {
							responseMap.put("resultCode", ResponseVo.ERROR_CODE);
							responseMap.put("message", "数据处理异常");
							//插入轨迹信息
							insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
						}
					}
				}
			}
		}
		return responseMap;
	}
	
	
	public Map<String, Object> synStatus_ZH(SynStatusModel statusVo,OrderMainEntity orderMain,String synStatus_url) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		String cancelChannel = orderMain.getCancelChannel(); //取消渠道：1-上游，2-下游，3-车服，4-C端
		String main_status = orderMain.getStatus(); //主服务单状态
		
		/**
		 * 下游服务商状态：
		 * V2.0：01内勤受理02派单03救援师傅接单04改派05救援师傅出发06救援师傅到达现场开始作业07施救完成（拖车已拖至目的地）08师傅报备取消09任务结束
		 */
		String serviceStatus = statusVo.getStatus();
		serviceStatus = StatusEnum.getName(serviceStatus);
		String statusTime = statusVo.getStatusTime();
		Date statusDate = DateUtil.stringToDate(statusTime, "yyyy-MM-dd HH:mm:ss");
		//中华的服务单
		//已完成、取消有费用、取消无费用的不做处理，只记录轨迹
		if("08".equals(main_status)||"10".equals(main_status)||"11".equals(main_status)){
			responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
			responseMap.put("message", ResponseVo.SUCCESS_MSG);
			if("10".equals(main_status)){
				logger.info("==========================中华救援单车服取消拦截，通知下游后，同步状态报文  start===================================");
				
				//中华救援单 因无取消通知接口 在车服取消拦截时无法通知渠道商  所以等下游同步状态时再同步上游
				//车服服务类型 转义 中华服务类型
				String serviceCode = TypeConverUtils.getServiceCode("02",orderMain.getServiceItem());
				Map<String,Object> requestBodyMap = new HashMap<String,Object>();
				requestBodyMap.put("workId", orderMain.getOwnerOrderNo());
				requestBodyMap.put("serviceCode", serviceCode);
				requestBodyMap.put("servicePerName", statusVo.getRescueName());
				requestBodyMap.put("servicePerPhone", statusVo.getRescuePhone());
				requestBodyMap.put("status", "404"); //供应商空驶费
				
				Double fee = PublicUtil.isNotEmpty(statusVo.getFee()) ? statusVo.getFee() : 0d;
				String feeStr = String.valueOf(fee);
				BigDecimal feeDecimal =new BigDecimal(feeStr);
				requestBodyMap.put("totalMoney", feeDecimal);
				
				Double judgeField = PublicUtil.isNotEmpty(statusVo.getVainDistance()) ? statusVo.getVainDistance() : 0d;
				if(judgeField>0){
					requestBodyMap.put("totalKilometer", String.valueOf(judgeField/1000));
				}else{
					requestBodyMap.put("totalKilometer", "0");
				}
				
				String jsonStr = JSON.toJSONString(requestBodyMap);
				logger.info("中华上游状态回传请求报文=" + jsonStr);
				logger.info("中华上游状态回传请求url=" + synStatus_url);
				String result = HttpClientUtil.getCodeResult(synStatus_url, jsonStr);  
				logger.info("中华上游状态回传响应报文=" + result);
				if(result == null || "".equals(result)){
					responseMap.put("resultCode", ResponseVo.ERROR_CODE);
					responseMap.put("message", "渠道商状态回写接口调用失败");
					//插入轨迹信息
					insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, CREATER, 1);
					return responseMap;
				}
				JSONObject json = JSONObject.parseObject(result);
		        String code =  json.get("code").toString();
		        String desc =  json.get("desc").toString();
		        if("200".equals(code)){ //00
		        	responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
					responseMap.put("message", ResponseVo.SUCCESS_MSG);
					//插入轨迹信息
					insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
				}else{
					if(PublicUtil.isNotEmpty(desc)&&desc.contains("工单状态不可逆向传递")){
						responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
						responseMap.put("message", ResponseVo.SUCCESS_MSG);
						//插入轨迹信息
						insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
					}else{
						responseMap.put("resultCode", ResponseVo.ERROR_CODE);
						responseMap.put("message", ResponseVo.ERROR_MSG);
						//插入轨迹信息
						insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
					}
		        }
		        logger.info("==========================中华救援单车服取消拦截，通知下游后，同步状态报文  end===================================");
			}
			insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);//插入轨迹信息
		}else if("09".equals(main_status)){//服务取消，说明上游、C端已触发过取消
			if("08".equals(statusVo.getStatus())|| "09".equals(statusVo.getStatus())){//下游回写师傅报备取消或任务结束，调上游回写状态和取消接口
				Double judgeField = "08".equals(statusVo.getStatus())?statusVo.getVainDistance():statusVo.getFee();
				judgeField = judgeField == null ? 0 : judgeField;
				String temp_judgeField = String.valueOf(judgeField);
				BigDecimal decimal =new BigDecimal(temp_judgeField);
				
				try {
					//02-中华 
					logger.info("==========================中华救援单车状态为服务取消，下游回写"+statusVo.getStatus()+"  start===================================");
					//车服服务类型 转义 中华服务类型
					String serviceCode = TypeConverUtils.getServiceCode("02",orderMain.getServiceItem());
					
					//	下游返回师傅报备取消、客户C端取消、或者在车服系统拦截取消，无空驶费用，也不用给上游回传状态。
					if(("08".equals(statusVo.getStatus())||"3".equals(cancelChannel)||"4".equals(cancelChannel))&&decimal.compareTo(new BigDecimal(0)) == 0){
						//main_status="09" 说明车服取消或者C端取消  且当前无空无费用
						//插入轨迹信息
						insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
						// 状态回写成功后根据服务单状态，判断是否给客户发送对应的通知短信
						updateOwnParams_V2(statusVo, orderMain);//更新车服系统对应的表字段
						responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
						responseMap.put("message", ResponseVo.SUCCESS_MSG);
					}else{
						Map<String,Object> requestBodyMap = new HashMap<String,Object>();
						requestBodyMap.put("workId", orderMain.getOwnerOrderNo());
						requestBodyMap.put("serviceCode", serviceCode);
						requestBodyMap.put("servicePerName", statusVo.getRescueName());
						requestBodyMap.put("servicePerPhone", statusVo.getRescuePhone());
						if("08".equals(statusVo.getStatus())){ //下游师傅取消报备 且存在空
							requestBodyMap.put("status", "404"); //供应商空驶费
						}else{//下游返回09-任务结束
							requestBodyMap.put("status", "304"); //供应商服务结束
						}
						
						Double fee = PublicUtil.isNotEmpty(statusVo.getFee()) ? statusVo.getFee() : 0d;
						String feeStr = String.valueOf(fee);
						BigDecimal feeDecimal =new BigDecimal(feeStr);
						requestBodyMap.put("totalMoney", feeDecimal);
						
						if(judgeField>0){
							requestBodyMap.put("totalKilometer", String.valueOf(judgeField/1000));
						}else{
							requestBodyMap.put("totalKilometer", "0");
						}
						
						String jsonStr = JSON.toJSONString(requestBodyMap);
						logger.info("中华上游状态回传请求报文=" + jsonStr);
						logger.info("中华上游状态回传请求url=" + synStatus_url);
						String result = HttpClientUtil.getCodeResult(synStatus_url, jsonStr);  
						logger.info("中华上游状态回传响应报文=" + result);
						if(result == null || "".equals(result)){
							responseMap.put("resultCode", ResponseVo.ERROR_CODE);
							responseMap.put("message", "渠道商状态回写接口调用失败");
							//插入轨迹信息
							insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, CREATER, 1);
							return responseMap;
						}
						JSONObject json = JSONObject.parseObject(result);
				        String code =  json.get("code").toString();
				        String desc =  json.get("desc").toString();
				        if("200".equals(code)){ //00
				        	responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
							responseMap.put("message", ResponseVo.SUCCESS_MSG);
							//插入轨迹信息
							insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
							// 状态回写成功后根据服务单状态，判断是否给客户发送对应的通知短信
							updateOwnParams_V2(statusVo, orderMain);//更新车服系统对应的表字段
							sendSmsService.sendSms(orderMain.getOrderNo());
						}else{
							if(PublicUtil.isNotEmpty(desc)&&desc.contains("工单状态不可逆向传递")){
								responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
								responseMap.put("message", ResponseVo.SUCCESS_MSG);
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
							}else{
								responseMap.put("resultCode", ResponseVo.ERROR_CODE);
								responseMap.put("message", ResponseVo.ERROR_MSG);
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
							}
				        }
					}
					logger.info("==========================中华救援单车状态为服务取消，下游回写"+statusVo.getStatus()+"  end===================================");
				} catch (Exception e) {
					responseMap.put("resultCode", ResponseVo.ERROR_CODE);
					responseMap.put("message", "数据处理异常");
					//插入轨迹信息
					insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
				}
			}else{//服务取消状态下，回写的其它状态码，车服只记录轨迹
				responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
				responseMap.put("message", ResponseVo.SUCCESS_MSG);
				insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);//插入轨迹信息
			}
		}else{//服务单中间状态
			if("05".equals(statusVo.getStatus())){ //05-师傅出发时，只改变车服状态，不回传上游
				responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
				responseMap.put("message", ResponseVo.SUCCESS_MSG);
				updateOwnParams(statusVo, orderMain);//更新车服系统对应的表字段
				insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);//插入轨迹信息
				sendSmsService.sendSms(orderMain.getOrderNo());
			}else if("09".equals(statusVo.getStatus())){//下游回写任务结束，此逻辑不通（正常情况下不会出现）
				responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
				responseMap.put("message", ResponseVo.SUCCESS_MSG);
				insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);//插入轨迹信息
			}else if("08".equals(statusVo.getStatus())){//下游回写师傅报备取消，调上游回写接口和取消接口
				Double judgeField = PublicUtil.isNotEmpty(statusVo.getVainDistance()) ? statusVo.getVainDistance() : 0d;
				String temp_judgeField = String.valueOf(judgeField);
				BigDecimal decimal =new BigDecimal(temp_judgeField);
				try {
					logger.info("==========================中华救援单车，下游回写师傅报备取消  start===================================");
					//车服服务类型 转义 中华服务类型
					String serviceCode = TypeConverUtils.getServiceCode("02",orderMain.getServiceItem());
					//	救援单师傅报备取消并返回取消无空驶费用时，则不用给上游回传状态；
					if("08".equals(statusVo.getStatus())&& decimal.compareTo(new BigDecimal(0)) == 0){
						//插入轨迹信息
						insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
						// 状态回写成功后根据服务单状态，判断是否给客户发送对应的通知短信
						updateOwnParams_V2(statusVo, orderMain);//更新车服系统对应的表字段
						responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
						responseMap.put("message", ResponseVo.SUCCESS_MSG);
					}else{
						Map<String,Object> requestBodyMap = new HashMap<String,Object>();
						requestBodyMap.put("workId", orderMain.getOwnerOrderNo());
						requestBodyMap.put("serviceCode", serviceCode);
						requestBodyMap.put("servicePerName", statusVo.getRescueName());
						requestBodyMap.put("servicePerPhone", statusVo.getRescuePhone());
						requestBodyMap.put("status", "404"); //供应商空驶费
						
						Double fee = PublicUtil.isNotEmpty(statusVo.getFee()) ? statusVo.getFee() : 0d;
						String feeStr = String.valueOf(fee);
						BigDecimal feeDecimal =new BigDecimal(feeStr);
						requestBodyMap.put("totalMoney", feeDecimal);
						
						if(judgeField>0){
							requestBodyMap.put("totalKilometer", String.valueOf(judgeField/1000));
						}else{
							requestBodyMap.put("totalKilometer", "0");
						}
						
						String jsonStr = JSON.toJSONString(requestBodyMap);
						logger.info("中华上游状态回传请求报文=" + jsonStr);
						logger.info("中华上游状态回传请求url=" + synStatus_url);
						String result = HttpClientUtil.getCodeResult(synStatus_url, jsonStr);  
						logger.info("中华上游状态回传响应报文=" + result);
						if(result == null || "".equals(result)){
							responseMap.put("resultCode", ResponseVo.ERROR_CODE);
							responseMap.put("message", "渠道商状态回写接口调用失败");
							//插入轨迹信息
							insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, CREATER, 1);
							return responseMap;
						}
						JSONObject json = JSONObject.parseObject(result);
				        String code =  json.get("code").toString();
				        String desc =  json.get("desc").toString();
				        if("200".equals(code)){ //00
				        	responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
							responseMap.put("message", ResponseVo.SUCCESS_MSG);
							//插入轨迹信息
							insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
							// 状态回写成功后根据服务单状态，判断是否给客户发送对应的通知短信
							updateOwnParams_V2(statusVo, orderMain);//更新车服系统对应的表字段
							sendSmsService.sendSms(orderMain.getOrderNo());
						}else{
							if(PublicUtil.isNotEmpty(desc)&&desc.contains("工单状态不可逆向传递")){
								responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
								responseMap.put("message", ResponseVo.SUCCESS_MSG);
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
							}else{
								responseMap.put("resultCode", ResponseVo.ERROR_CODE);
								responseMap.put("message", ResponseVo.ERROR_MSG);
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
							}
				        }
					}
					logger.info("==========================中华救援单车，下游回写师傅报备取消  end===================================");
				} catch (Exception e) {
					responseMap.put("resultCode", ResponseVo.ERROR_CODE);
					responseMap.put("message", "数据处理异常");
					//插入轨迹信息
					insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
				}
			}else{ //下游回写的其它状态，直接回写上游
				try {
					//02-中华
					//车服服务类型 转义 中华服务类型
					String serviceCode = TypeConverUtils.getServiceCode("02",orderMain.getServiceItem());
					if("02".equals(statusVo.getStatus())||"06".equals(statusVo.getStatus())||"07".equals(statusVo.getStatus())){
						String status = "";
						if("02".equals(statusVo.getStatus())){  // 02派单
							status = "301"; //供应商已派单
						}else if("06".equals(statusVo.getStatus())){ // 06救援师傅到达现场开始作业
							status = "302"; //供应商已到达
						}else if("07".equals(statusVo.getStatus())){ // 07施救完成（拖车已拖至目的地）
							status = "304"; //供应商服务结束
						}
						
						Map<String,Object> requestBodyMap = new HashMap<String,Object>();
						requestBodyMap.put("workId", orderMain.getOwnerOrderNo());
						requestBodyMap.put("serviceCode", serviceCode);
						requestBodyMap.put("servicePerName", statusVo.getRescueName());
						requestBodyMap.put("servicePerPhone", statusVo.getRescuePhone());
						requestBodyMap.put("status", status);
						requestBodyMap.put("totalMoney", 0d);
						requestBodyMap.put("totalKilometer", "0");
						
						String jsonStr = JSON.toJSONString(requestBodyMap);
						logger.info("中华上游状态回传请求报文=" + jsonStr);
						logger.info("中华上游状态回传请求url=" + synStatus_url);
						String result = HttpClientUtil.getCodeResult(synStatus_url, jsonStr);
						logger.info("中华上游状态回传响应报文 sendPost=" + result);
						
						if(result == null || "".equals(result)){
							responseMap.put("resultCode", ResponseVo.ERROR_CODE);
							responseMap.put("message", "渠道商状态回写接口调用失败");
							//插入轨迹信息
							insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, CREATER, 1);
							return responseMap;
						}
						JSONObject json = JSONObject.parseObject(result);
				        String code =  json.get("code").toString();
				        String desc =  json.get("desc").toString();
				        if("200".equals(code)){ //00
				        	responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
							responseMap.put("message", ResponseVo.SUCCESS_MSG);
							//插入轨迹信息
							insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
							// 状态回写成功后根据服务单状态，判断是否给客户发送对应的通知短信
							updateOwnParams_V2(statusVo, orderMain);//更新车服系统对应的表字段
							sendSmsService.sendSms(orderMain.getOrderNo());
						}else{
							if(PublicUtil.isNotEmpty(desc)&&desc.contains("工单状态不可逆向传递")){
								responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
								responseMap.put("message", ResponseVo.SUCCESS_MSG);
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
							}else{
								responseMap.put("resultCode", ResponseVo.ERROR_CODE);
								responseMap.put("message", ResponseVo.ERROR_MSG);
								//插入轨迹信息
								insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
							}
				        }
					}else{ //其余状态只更新服务单以及记录
						responseMap.put("resultCode", ResponseVo.SUCCESS_CODE);
						responseMap.put("message", ResponseVo.SUCCESS_MSG);
						//插入轨迹信息
						insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 0);
						// 状态回写成功后根据服务单状态，判断是否给客户发送对应的通知短信
						updateOwnParams_V2(statusVo, orderMain);//更新车服系统对应的表字段
					}
				} catch (Exception e) {
					responseMap.put("resultCode", ResponseVo.ERROR_CODE);
					responseMap.put("message", "数据处理异常");
					//插入轨迹信息
					insertSynStatusTrack(orderMain, statusVo, main_status, serviceStatus, statusDate, statusVo.getRescueName(), 1);
				}
			}
		}
		return responseMap;
	}
	
	// 2022年1月4日 保存状态回写轨迹记录：flag：0:成功标识，1:失败标识
	public void insertSynStatusTrack_V2(OrderMainEntity orderMain, SynStatusModel statusVo, String main_status,
			String serviceStatus, Date statusDate, String creater, int flag) {
		String track_status = "";
		if ("1".equals(flag)) {
			track_status = main_status;
		} else {
		  switch (statusVo.getStatus()) {
			case "01": // 内勤受理
				if (!("08".equals(main_status) || "09".equals(main_status) || "10".equals(main_status) || "11".equals(main_status))) {
					track_status = "02";
				} else {
					track_status = main_status;
				}
				break;
			case "02": // 派单
				CREATER = statusVo.getWorkerName();
				if (!("08".equals(main_status) || "09".equals(main_status) || "10".equals(main_status) || "11".equals(main_status))) {
					track_status = "03";
				} else {
					track_status = main_status;
				}
				break;
			case "03": // 救援师傅接单
				if (!("08".equals(main_status) || "09".equals(main_status) || "10".equals(main_status) || "11".equals(main_status))) {
					track_status = "04";
				} else {
					track_status = main_status;
				}
				break;
			case "04": // 改派
				CREATER = statusVo.getWorkerName();
				if (!("08".equals(main_status) || "09".equals(main_status) || "10".equals(main_status) || "11".equals(main_status))) {
					track_status = "04";
				} else {
					track_status = main_status;
				}
				break;
			case "05": // 05救援师傅出发
				if (!("08".equals(main_status) || "09".equals(main_status) || "10".equals(main_status) || "11".equals(main_status))) {
					track_status = "05";
				} else {
					track_status = main_status;
				}
				break;
			case "06": // 救援师傅到达现场开始作业
				if (!("08".equals(main_status) || "09".equals(main_status) || "10".equals(main_status) || "11".equals(main_status))) {
					track_status = "06";
				} else {
					track_status = main_status;
				}
				break;
			case "07": // 施救完成（拖车已拖至目的地）
				if (!("08".equals(main_status) || "09".equals(main_status) || "10".equals(main_status) || "11".equals(main_status))) {
					track_status = "08";
				} else {
					track_status = main_status;
				}
				break;
			case "08": // 师傅报备取消
				if (!("08".equals(main_status) || "09".equals(main_status) || "10".equals(main_status) || "11".equals(main_status))) {
					track_status = "09";
				} else {
					track_status = main_status;
				}
				break;
			case "09": // 任务结束
				track_status = main_status;
				break;
		  }
		}
		OrderTrackEntity vo = new OrderTrackEntity();
		vo.setDataId(PubUtils.uuid());
		vo.setOrderNo(orderMain.getOrderNo());
		vo.setTrackType("01"); // 轨迹类型：下单备注00、救援轨迹01、催单备注02、取消备注03，用于区分备注轨迹还是救援轨迹
		vo.setTrackDesc(statusVo.getCancelReason());// 轨迹描述：下单备注内容、救援轨迹描述、催单接口的催单内容、取消接口的取消原因
		// 以下两个字段，上游到下游可以为空，下游到上游，需赋值，用于计算是否为延时单和轨迹展示
		vo.setStatus(track_status); // 服务单主表的状态码
		vo.setServiceStatus(serviceStatus);
		vo.setCreateTime(new Date());
		vo.setUpdateTime(new Date());
		vo.setCreater(creater);
		vo.setUpdater(creater);
		vo.setIsDelete(flag);
		if (PublicUtil.isEmpty(statusDate)) {
			vo.setSynTime(new Date());
		} else {
			vo.setSynTime(statusDate); // 报文中的时间
		}
		orderTrackDao.insert(vo);
	}
	
	public void updateOwnParams_V2(SynStatusModel statusVo, OrderMainEntity orderMain) {
		String dataId = orderMain.getDataId(); //车服系统主键，用于更新服务单主表信息
		String serviceStatus = statusVo.getStatus();
		serviceStatus = StatusEnum.getName(serviceStatus);
		String statusTime = statusVo.getStatusTime();
		Date statusDate = DateUtil.stringToDate(statusTime, "yyyy-MM-dd HH:mm:ss");
		String main_status = orderMain.getStatus();
		Map<String,Object> params = new HashMap<>(); //查询map参数集合
		int differ = 0; //存时间差，判断是否为延时单
		Map<String, Object> provider_param = new HashMap<>(); //更新t_order_service_provider表参数
		Map<String, Object> rescue_param = new HashMap<>();   //更新t_order_service_rescue表参数
		// 救援人员转译：鹏达救援 ==> 救援商A，值取自服务商表中存的救援商转译
		String rescueName = statusVo.getRescueName();
		if (PublicUtil.isNotEmpty(rescueName)) {
			Map<String, Object> rescueNameParam = new HashMap<>();
			rescueNameParam.put("shiftName", rescueName);
			ServiceProviderEntity serviceProviderEntity = serviceProviderDao.getOneByParams(rescueNameParam);
			if (PublicUtil.isNotEmpty(serviceProviderEntity)) {
				rescueName = serviceProviderEntity.getServiceName();
			}
		} else {
			rescueName = serverName; // TODO 经确认，若没有传救援人员，则默认为救援商A
		}
		//该为不判断状态码，有值就更新，没值不更新
		provider_param.put("workerName", statusVo.getWorkerName());
		provider_param.put("orderNo", orderMain.getOrderNo());
		provider_param.put("rescueName", rescueName);
		provider_param.put("rescuePhone", statusVo.getRescuePhone());
		provider_param.put("fee", statusVo.getFee());
		orderServiceProviderService.updateByParams(provider_param);
		rescue_param.put("orderNo", orderMain.getOrderNo());
		rescue_param.put("sendX", statusVo.getSendX());
		rescue_param.put("sendY", statusVo.getSendY());
		rescue_param.put("arriveX", statusVo.getArriveX());
		rescue_param.put("arriveY", statusVo.getArriveY());
		rescue_param.put("endX", statusVo.getArriveX()); //新增的endX、endY，完成（拖车目的地）经纬度
		rescue_param.put("endY", statusVo.getArriveY());
		rescue_param.put("dragDistance", statusVo.getDragDistance());
		rescue_param.put("rescueDistance", statusVo.getDragDistance());
		rescue_param.put("serviceItem", statusVo.getServiceItem());
		rescue_param.put("longitude", statusVo.getLongitude());
		rescue_param.put("latitude", statusVo.getLatitude());
		rescue_param.put("address", statusVo.getAddress());
		orderServiceRescueService.updateByParams(rescue_param);
		switch (statusVo.getStatus()) {
			case "01": // 内勤受理
				CREATER = statusVo.getWorkerName();
				if( !("08".equals(main_status) || "09".equals(main_status) || "10".equals(main_status) || "11".equals(main_status)) ) {
					orderMainService.updateStatus(dataId, "02", new Date(), statusVo.getRescueName());// 更新服务单主表状态：待处理--->已受理
				}
				break;
			case "02": // 派单
				CREATER = statusVo.getWorkerName();
				if( !("08".equals(main_status) || "09".equals(main_status) || "10".equals(main_status) || "11".equals(main_status)) ) {
					orderMainService.updateStatus(dataId, "03", new Date(), statusVo.getRescueName());// 更新服务单主表状态：已派单
				}
				break;
			case "03": // 救援师傅接单
				CREATER = rescueName;
				if( !("08".equals(main_status) || "09".equals(main_status) || "10".equals(main_status) || "11".equals(main_status)) ) {
					orderMainService.updateStatus(dataId, "04", new Date(), statusVo.getRescueName());// 更新服务单主表状态：已接单
				}
				// 查找服务单在'已受理'状态时的轨迹时间，计算时间差，处理时长超过5分钟则为延时单
				params.put("orderNo", orderMain.getOrderNo());
				params.put("trackType", "01");
				params.put("serviceStatus", "内勤受理");
				OrderTrackEntity orderTrackEntity = this.getOneByParams(params);
				if (orderTrackEntity != null) {
					Date synTime = orderTrackEntity.getSynTime();
					differ = DateUtil.getIntervalFen(synTime, statusDate);
					if (differ >= DelayedConfig.ONE /*&& orderMain.getIsDalayed() == 0*/) { // 更新服务单主表信息延时标识
						orderMainService.updateDelayedFlag(dataId);
					}else if(differ < DelayedConfig.ONE/* && orderMain.getIsDalayed() == 1*/){//将延时标识取消
						orderMainService.delDelayedFlag(dataId);
					}
				}
				break;
			case "04": // 改派
				CREATER = rescueName;
				if( !("08".equals(main_status) || "09".equals(main_status) || "10".equals(main_status) || "11".equals(main_status)) ) {
					orderMainService.updateStatus(dataId, "04", new Date(), statusVo.getRescueName());// 更新服务单主表状态：已接单
				}
				break;
			case "05": // 05救援师傅出发
				CREATER = rescueName;
				if( !("08".equals(main_status) || "09".equals(main_status) || "10".equals(main_status) || "11".equals(main_status)) ) {
					orderMainService.updateStatus(dataId, "05", new Date(), statusVo.getRescueName());// 更新服务单主表状态：开始出发
				}
				break;
			case "06": // 救援师傅到达现场开始作业
				CREATER = rescueName;
				if( !("08".equals(main_status) || "09".equals(main_status) || "10".equals(main_status) || "11".equals(main_status)) ) {
					orderMainService.updateStatus(dataId, "06", new Date(), statusVo.getRescueName());// 更新服务单主表状态：到达现场
				}
				// 查找服务单在'已接单'状态时的轨迹时间，计算时间差，处理时长超过45分钟则为延时单
				params.put("orderNo", orderMain.getOrderNo());
				params.put("trackType", "01");
				params.put("serviceStatus", "救援师傅接单");
				orderTrackEntity = this.getOneByParams(params);
				if (orderTrackEntity != null) {
					Date synTime = orderTrackEntity.getSynTime();
					differ = DateUtil.getIntervalFen(synTime, statusDate);
					if (differ >= DelayedConfig.TWO/* && orderMain.getIsDalayed() == 0*/) { // 延时单标识，默认0-非延时，1-延时
						orderMainService.updateDelayedFlag(dataId);// 更新服务单主表信息延时标识
					}else if(differ < DelayedConfig.TWO && orderMain.getIsDalayed() == 2){//将延时标识取消
						orderMainService.delDelayedFlag(dataId);
					}
				}
				break;
			case "07": // 施救完成（拖车已拖至目的地）
				CREATER = rescueName;
				// 更新服务单主表状态：已完成
				if( !("08".equals(main_status) || "09".equals(main_status) || "10".equals(main_status) || "11".equals(main_status)) ) {
					orderMainService.updateStatus(dataId, "08", new Date(), statusVo.getRescueName());// 更新服务单主表状态：已完成
				}
				break;
			case "08": // 师傅报备取消
				CREATER = rescueName;
				if( !("08".equals(main_status) /*|| "09".equals(main_status)*/ || "10".equals(main_status) || "11".equals(main_status)) ){
					//判断vainDistance字段的值
					Double judgeField = PublicUtil.isNotEmpty(statusVo.getVainDistance()) ? statusVo.getVainDistance() : 0d;
					String temp_judgeField = String.valueOf(judgeField);
					BigDecimal decimal =new BigDecimal(temp_judgeField);
					if(decimal.compareTo(new BigDecimal(0))>0){
						orderMainService.updateStatus(dataId, "10", new Date(), statusVo.getRescueName());//10-取消有费用
					}else{
						orderMainService.updateStatus(dataId, "11", new Date(), statusVo.getRescueName());//11-取消无费用
					}
				}
				break;
			case "09": // 任务结束
				CREATER = rescueName;
				if( "09".equals(main_status) ){
					//判断fee字段的值
					Double judgeField = PublicUtil.isNotEmpty(statusVo.getFee()) ? statusVo.getFee() : 0d;
					String temp_judgeField = String.valueOf(judgeField);
					BigDecimal decimal =new BigDecimal(temp_judgeField);
					if(decimal.compareTo(new BigDecimal(0))>0){
						orderMainService.updateStatus(dataId, "10", new Date(), statusVo.getRescueName());//10-取消有费用
					}else{
						orderMainService.updateStatus(dataId, "11", new Date(), statusVo.getRescueName());//11-取消无费用
					}
				}
				break;
			default:
				break;
		}
		logger.info("---------------------本地状态更新成功---------------------");
	}

}
